package com.example.news_reader;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.Toast;
import android.widget.ExpandableListView.OnChildClickListener;

public class NewsMain extends Activity {
		private ArrayList<String> mGroupList = null;    
		private ArrayList<ArrayList<DataList>> mChildList = null;    
		private ExpandableListView mListView=null;
		private C_Adapter adapter = null;
		private final int DID = 0;
		private final int WHAT = 0;
		private NewsList nList = null;
		EditText text;
		int cnt=0;
		
		Handler handler = new Handler(){
			public void handleMessage(Message msg){
				switch (msg.what){
					case WHAT:
						mListView.setAdapter(adapter);

						// 차일드 클릭 했을 경우 이벤트        
						mListView.setOnChildClickListener(new OnChildClickListener() {             
							@Override            
							public boolean onChildClick(ExpandableListView parent, View v,                     
									int groupPosition, int childPosition, long id) {   
								String link = mChildList.get(groupPosition).get(childPosition).getLink();
								if(link!=null){
								Intent i = new Intent(NewsMain.this, WebLink.class);
								i.putExtra("link", link);
								startActivity(i);
								}
								return false;             
							}         
						});                   

						int cnt = mListView.getCount();
						for(int i=0; i<cnt; i++){
							mListView.expandGroup(i);
						}

						removeDialog(DID);
						break;
				}
			}
		};

		@Override
		public boolean onKeyDown(int keyCode, KeyEvent event) {
			// TODO Auto-generated method stub
			//return super.onKeyDown(keyCode, event);
			if (keyCode == KeyEvent.KEYCODE_BACK&&event.getRepeatCount()==0)
			{
				AlertDialog.Builder bld = new AlertDialog.Builder(this);
				bld.setTitle("종료");
				bld.setMessage("종료하시겠습니까?");
				bld.setPositiveButton("예", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						moveTaskToBack(true);
						stopService(new Intent("org.cherry.namespace.mymp3"));
						finish();
					}
				});
				bld.setNegativeButton("아니오",null);
				bld.show();
				return true; 
			}
			return super.onKeyDown(keyCode, event);
		}

		@Override
		public boolean onCreateOptionsMenu(Menu menu) {
			// TODO Auto-generated method stub
			menu.add(Menu.NONE, Menu.FIRST+1, Menu.NONE, "언론사 선택");
			menu.add(Menu.NONE, Menu.FIRST+2, Menu.NONE, "카테고리 선택");
			menu.add(Menu.NONE, Menu.FIRST+3, Menu.NONE, "키워드 검색");
			return super.onCreateOptionsMenu(menu);
		}

		@Override
		public boolean onOptionsItemSelected(MenuItem item) {
			// TODO Auto-generated method stub
			boolean a = false;

			switch(item.getItemId()){
				case Menu.FIRST+1:
					showDialog(DID+1);
				a=true;
				break;
				case Menu.FIRST+2:
					showDialog(DID+2);
				a=true;
				break;
				case Menu.FIRST+3:
					showDialog(DID+3);
				a=true;
				break;
			}

			return (a || super.onOptionsItemSelected(item));
		}

		@Override   
		public void onCreate(Bundle savedInstanceState) {       
			super.onCreate(savedInstanceState);       
			setContentView(R.layout.main);         
			mListView = (ExpandableListView)findViewById(R.id.news_lv);
			Display display = getWindowManager().getDefaultDisplay();
			int width = display.getWidth();
			mListView.setIndicatorBounds(width-50, width);
			//		mListView.setGroupIndicator(null);

			nList = new NewsList(this);

			runData();

		}       


		protected void runData(){
			showDialog(DID);
			Thread thread = new Thread(){
				public void run(){

					mGroupList = new ArrayList<String>();   
					
					mGroupList.add("Top News");
					mGroupList.add("category");
					mGroupList.add("keyword");
					
					mChildList = new ArrayList<ArrayList<DataList>>();
					ArrayList<DataList> mCList = new ArrayList<DataList>();
					
					//종합
					DataParsing parser;
					String url = "http://news.google.co.kr/news?q="+
							"&hl=ko&newwindow=1&prmd=imvnsul&bav=on.2,or.r_gc.r_pw.r_qf.&biw=1600&bih=809&um=1&ie=UTF-8&output=rss";
					parser = new DataParsing(url);
					mCList = parser.getAllData();
					mChildList.add(mCList);
					
					//카테고리
					ArrayList<String> mList = nList.getCategoryName();
					mCList = new ArrayList<DataList>();
					
					for(int i=0;i<mList.size();i++){
						parser = new DataParsing(nList.getNews_url(i));
						ArrayList<DataList> pList = parser.getAllData(mList.get(i));
						if(mCList.size()==0)
							mCList = pList;
						else{
							for(int j=0;j<pList.size();j++){
								mCList.add(pList.get(j));
							}
						}
					}
					mChildList.add(mCList);
					
					//검색
					mCList = new ArrayList<DataList>();
					if(nList.getKey()!=null){
					String query = null;

					try {
						query = URLEncoder.encode(nList.getKey(), "utf-8");
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					url = "http://news.google.co.kr/news?q="+
							query+
							"&hl=ko&newwindow=1&prmd=imvnsul&bav=on.2,or.r_gc.r_pw.r_qf.&biw=1600&bih=809&um=1&ie=UTF-8&output=rss";
					parser = new DataParsing(url);
					mCList = parser.getAllData();
					}else{
						mGroupList.remove(2);
						mCList.add(new DataList("검색결과가 없습니다.", null, "", ""));
					}
					mChildList.add(mCList);
					adapter = new C_Adapter(NewsMain.this, mGroupList, mChildList);
					Message msg = handler.obtainMessage(WHAT);
					handler.sendMessage(msg);
				}
			};
			thread.start();
		}

		protected Dialog onCreateDialog(int id){
			ProgressDialog d = new ProgressDialog(this);
			AlertDialog.Builder b = new AlertDialog.Builder(NewsMain.this);
			AlertDialog alert;
			switch(id){
				case DID:
					d.setMessage("Loding...");
					d.setIndeterminate(true);
					d.setCancelable(true);
					return d;
				case DID+1:
					b.setTitle("언론사를 선택하세요.");
				b.setSingleChoiceItems(R.array.news, 0, new OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						nList.setCntN(which);
					}
				});
				b.setPositiveButton("확인", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						runData();  
					}});
				b.setNegativeButton("취소", null);
				alert = b.create();
				return alert;
				case DID+2:
					cnt=0;
					nList.setCntCAll();
					b.setTitle("카테고리를 선택하세요.");
				b.setMultiChoiceItems(R.array.category, null, new DialogInterface.OnMultiChoiceClickListener() {

					@Override 
					public void onClick(DialogInterface dialog, int which, boolean isChecked) {
						nList.setCntC(which, isChecked);
						cnt++;
						Log.i("which",which+"");
						Log.i("checked",isChecked+"");
					}
				});
				b.setPositiveButton("확인", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						if(cnt==0){
							Toast t = Toast.makeText(NewsMain.this, "카테고리를 선택하세요.", Toast.LENGTH_LONG);
							nList.setCntC(0, true);
							t.show();
						}else{
							runData();  
						}
					}});
				b.setNegativeButton("취소", null);
				alert = b.create();
				return alert;
				case DID+3:
					b.setTitle("키워드를 입력해 주세요.");
				text = new EditText(NewsMain.this);
				b.setView(text);
				
				b.setPositiveButton("확인", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						String a = text.getText().toString();
						nList.setKey(a);
						runData();					
					}
				});
				b.setNegativeButton("취소", null);
				alert = b.create();
				return alert;

			}
			return d;
		}
	}
